package com.qzsoft.zhjd.common.utils;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.qzsoft.jeemis.common.utils.DateUtils;
import com.qzsoft.jeemis.common.utils.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.BeanUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class ManyExcelExportUtils extends ExcelUtils {

    public ManyExcelExportUtils() {
    }

    public static void exportExcel(HttpServletResponse response, String fileName, String title,
                                   String sheetName, Collection<?> list, Class<?> pojoClass, Object t) throws IOException {
        if (StringUtils.isBlank(fileName)) {
            fileName = DateUtils.format(new Date());
        }
        ExportParams params = new ExportParams(title, sheetName, ExcelType.XSSF);
        Workbook workbook = CustomExcelExport.exportExcel(params, pojoClass, list,t);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    }

    public static void exportExcelToTarget(HttpServletResponse response, String fileName, String title, String sheetName, Collection<?> sourceList, Class<?> targetClass, Object t) throws Exception {
        List targetList = new ArrayList(sourceList.size());
        Iterator var8 = sourceList.iterator();

        while(var8.hasNext()) {
            Object source = var8.next();
            Object target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            targetList.add(target);
        }
        exportExcel(response, fileName, title, sheetName, targetList, targetClass, t);
    }

    public static void exportEchartImage(HttpServletResponse response, String fileName, SXSSFWorkbook wb, CountTopData countNums) throws Exception {
        if (StringUtils.isBlank(fileName)) {
            fileName = DateUtils.format(new Date());
        }
        SXSSFWorkbook workbook = CustomExcelExport.msgExportExcel(wb,countNums);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    }
}
